package com.liyunc.demo.base.component;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JComboBoxExample {
    public static void main(String[] args) {
        JFrame jf = new JFrame("测试窗口");
        jf.setSize(250, 250);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();

        //添加一个标签
        JLabel jLabel = new JLabel("水果");
        panel.add(jLabel);

        String[] data = {"香蕉", "苹果", "桃子", "西瓜"};

        JComboBox<String> jComboBox = new JComboBox<>(data);

        jComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 只处理选中的状态
                System.out.println("选中: " + jComboBox.getSelectedIndex() + " = " + jComboBox.getSelectedItem());
            }
        });

        // 设置默认选中的条目
        jComboBox.setSelectedIndex(2);

        // 添加到内容面板
        panel.add(jComboBox);

        jf.setContentPane(panel);
        jf.setVisible(true);
    }
}
